package com.book.controller.reader;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.book.core.util.ExcelUtil;
import com.book.core.domain.Readers;
import com.book.core.mode.R;
import com.book.core.query.ReaderQuery;
import com.book.core.vo.PageVO;
import com.book.listener.GenericExcelDataListener;
import com.book.service.ReadersService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/reader")
@RequiredArgsConstructor
public class ReaderController {
    private final ReadersService readersService;

    @GetMapping("/page")
    public R<PageVO<Readers>> getReaderPage(ReaderQuery query) {
        return R.ok(readersService.getReaderPage(query));
    }

    @PostMapping
    public R<String> saveReader(@RequestBody @Validated Readers readers) {
        readersService.save(readers);
        return R.ok("保存成功",null);
    }
    @PutMapping
    public R<String> updateReader(@RequestBody @Validated Readers readers) {
        readersService.updateById(readers);
        return R.ok("修改成功",null);
    }
    @DeleteMapping("/{id}")
    public R<String> deleteReader(@PathVariable Integer id) {
        readersService.removeById(id);
        return R.ok("删除成功",null);
    }
    @GetMapping("/{id}")
    public R<Readers> getReader(@PathVariable Integer id) {
        return R.ok(readersService.getById(id));
    }
    @GetMapping("/count")
    public R<Long> getReaderCount() {
        return R.ok(readersService.count());
    }
    @GetMapping("/export")
    public void exportBookExcel(HttpServletResponse response) throws IOException {
        // 1. 设置响应头
        ExcelUtil.setExcelResponseHeader(response, "读者列表");
        // 2. 分页查询数据（避免内存溢出）
        int pageSize = 1000; // 每页1000条
        int pageNum = 1;
        boolean hasNext = true;
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                .head(Readers.class)
                .excelType(ExcelTypeEnum.XLSX)
                .build();
        WriteSheet writeSheet = EasyExcel.writerSheet("图书列表").build();
        // 3. 分批写入Excel
        while (hasNext) {
            List<Readers> batchList = readersService.lambdaQuery().page(new Page<>(pageNum, pageSize)).getRecords();
            if (batchList.isEmpty()) {
                hasNext = false;
            } else {
                excelWriter.write(batchList, writeSheet);
                pageNum++;
            }
        }
        excelWriter.finish();
    }
    @PostMapping("/import")
    public R<String> importBookExcel(@RequestParam("file") MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Readers.class, new GenericExcelDataListener<Readers>(readersService)).sheet().doRead();
        return R.ok("导入成功",null);
    }
}
